#!/usr/local/bin/python
# -*- coding: utf-8 -*-


"""下载微信好友头像

头像默认保存在test文件夹下
"""

import itchat
import PIL.Image as Image
import math


itchat.auto_login(hotReload=True)

friends = itchat.get_friends(update=True)   # 核心：得到friends列表集，内含很多信息


for n, f in enumerate(friends, 1):
    img = itchat.get_head_img(userName=f["UserName"])
    with open("images/%d.jpg" % n, 'wb') as fileImage:
        fileImage.write(img)
print("所有好友头像数：%d" % n)

# 构造头像拼图
eachsize = int(math.sqrt(640 * 640 / num))    # 先圈定每个正方形小头像的边长，如果嫌小可以加大
print("小正方形头像边长：%d" % eachsize)
numrow = int(640 / eachsize)
print("一行小头像数：%d" % numrow)
numcol = int(math.ceil(num / numrow))   # 向上取整
x = 0   # 小头像拼接时的左上角横坐标
y = 0   # 小头像拼接时的左上角纵坐标
for i in range(num):
    try:
        #打开图片
        img = Image.open("images/%d.jpg"%i)
    except IOError:
        print("Error: 没有找到文件或读取文件失败")
    else:
        img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
        x += 1
        if x == numrow:
            x = 0
            y += 1

# itchat.send_image(str(user / "x.jpg"), 'filehelper')